package com.ruoyi.alert.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Configuration
public class RabbitMQConfig {

    // 添加交换器和死信队列定义
    public static final String DLX_EXCHANGE = "alarm.dead.letter.exchange";
    public static final String DLX_QUEUE = "alarm.dead.letter.queue";
    public static final String DLX_ROUTING_KEY = "alarm.dead.letter.routingkey";

    // 创建死信交换器
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(DLX_EXCHANGE);
    }

    // 创建死信队列
    @Bean
    public Queue dlxQueue() {
        return new Queue(DLX_QUEUE, true);
    }


    @Bean
    public Queue alarmQueue() {
        return new Queue("alarm.queue", true, false, false,
                new HashMap<String, Object>() {{
                    put("x-message-ttl", 60000);
                    put("x-dead-letter-exchange", "alarm.dead.letter.exchange");
                    put("x-dead-letter-routing-key", "alarm.dead.letter.routingkey");
                }});
    }


    // 绑定死信队列
    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue())
                .to(dlxExchange())
                .with(DLX_ROUTING_KEY);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(producerMessageConverter()); // 绑定转换器
        return rabbitTemplate;
    }

    // 创建普通交换器
    @Bean
    public DirectExchange alarmExchange() {
        return new DirectExchange("alarm.exchange");
    }

    // 绑定队列到交换器
    @Bean
    public Binding alarmBinding(Queue alarmQueue, DirectExchange alarmExchange) {
        return BindingBuilder.bind(alarmQueue)
                .to(alarmExchange)
                .with("alarm.routingkey");
    }



    // 注入回调配置
//    @PostConstruct
//    public void init() {
//        rabbitTemplate.setConfirmCallback(confirmCallback());
//    }





    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return (correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息成功发送到Exchange");
            } else {
                System.out.println("消息发送失败: " + cause);
            }
        };
    }

    @Bean
    public Jackson2JsonMessageConverter producerMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}